package com.shxzz.easy12306.services.ticket.service.handler.filter.query;

import com.shxzz.easy12306.framework.starter.cache.StringRedisTemplateProxy;
import com.shxzz.easy12306.framework.starter.convention.exceptions.ClientException;
import com.shxzz.easy12306.services.ticket.common.constant.RedisKeyConstant;
import com.shxzz.easy12306.services.ticket.dto.req.TicketPageQueryReqDTO;
import com.shxzz.easy12306.services.ticket.service.cache.StationCodeCacheLoader;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 车票查询参数-始发站、目的站存在性校验
 *
 * @author shxzz
 * @create 2024-03-06-14:26
 */
@RequiredArgsConstructor
@Component
public class TicketSearchParamStationVerifyChainFilter implements TicketSearchChainFilter {

    private final StringRedisTemplateProxy stringRedisTemplateProxy;

    private final StationCodeCacheLoader stationCodeCacheLoader;

    @Override
    public void handler(TicketPageQueryReqDTO requestParam) {
        StringRedisTemplate stringRedisTemplate = stringRedisTemplateProxy.getInstance();
        List<Object> stations = new ArrayList<>(Arrays.asList(requestParam.getToStation(), requestParam.getFromStation()));
        List<Object> names = stringRedisTemplate.opsForHash().multiGet(RedisKeyConstant.ALL_STATION_CODE_INFO, stations);
        long count = names.stream().filter(Objects::isNull).count();
        if (count == 0) {
            return;
        }
        if (count == 1 || (count == 2 && stringRedisTemplate.hasKey(RedisKeyConstant.ALL_STATION_CODE_INFO))) {
            throw new ClientException("出发站点或目的站点不存在");
        }
        count = Optional.ofNullable(stationCodeCacheLoader.getAndLoad(stations))
                .map(each -> each.stream().filter(Objects::isNull).count())
                .orElse(0L);
        if(count > 0) {
            throw new ClientException("出发站点或目的站点不存在");
        }
    }

    @Override
    public int getOrder() {
        return 200;
    }
}
